import datetime

from pydantic import BaseModel, Field, root_validator, validator

from enums.client_user_enum import UserGenderTypeEnum, UserRegisterTypeEnum


class AddNewClientUserRequestModel(BaseModel):

    tenant_id: int = Field(None, description="租户id")
    username: str = Field(None, description="用户名", max_length=32)
    alias: str = Field(None, description="用户别名", max_length=16)
    password: str = Field(..., description="密码", min_length=6, max_length=16)
    re_password: str = Field(..., description="重复密码", min_length=6, max_length=16)
    email: str = Field(None, max_length=64, description="邮箱")
    phone: str = Field(None, max_length=16, description="手机号")
    avatar: str = Field(None, description="用户头像", max_length=128)
    description: str = Field(None, description="用户描述", max_length=255)
    gender: UserGenderTypeEnum = Field(None, description="用户性别")
    birthday: datetime.date = Field(None, description="用户生日")
    invited_code: str = Field(None, description="用户的受邀码", max_length=10)
    register_type: UserRegisterTypeEnum = Field(..., description="注册方式")

    invite_code: str = Field(None, description="邀请码", max_length=10)

    @root_validator()
    def validate_root(cls, attrs: dict):
        register_type = attrs.get("register_type")
        password = attrs.get("password")
        re_password = attrs.get("re_password")
        birthday = attrs.get("birthday")
        if birthday:
            cls._validate_birthday(birthday)
        assert password == re_password, "两次密码不一致"
        if register_type == UserRegisterTypeEnum.email:
            cls._validate_email_type(attrs)
        elif register_type == UserRegisterTypeEnum.phone:
            cls._validate_phone_type(attrs)
        else:
            ...
        return attrs

    @classmethod
    def _validate_email_type(cls, attrs):
        if "email" not in attrs:
            raise ValueError("缺失参数")

    @classmethod
    def _validate_phone_type(cls, attrs):
        if "phone" not in attrs:
            raise ValueError("缺失参数")

    @classmethod
    def _validate_birthday(cls, birthday):
        b = datetime.datetime.strptime(birthday, "%Y-%m-%d")
        now = datetime.datetime.now()
        assert now > b, "请输入正确的出生年月"


class ClientUserLoginRequestModel(BaseModel):
    email: str = Field(..., max_length=32, description="用户邮箱")
    password: str = Field(..., max_length=16, min_length=6, description="用户密码")
